import Vue from "vue";
import PrivacyPopup from "@/components/shopro-privacy-popup/shopro-privacy-popup.vue";

const PrivacyService = {
  instance: null,

  init(vmContext) {
    if (this.instance) return;

    // 确保在DOM准备好后执行
    return new Promise((resolve) => {
      Vue.nextTick(() => {
        const PrivacyComponent = Vue.extend(PrivacyPopup);
        this.instance = new PrivacyComponent({
          parent: vmContext,
        });

        const el = document.createElement("div");
        document.body.appendChild(el);
        this.instance.$mount(el);
        resolve();
      });
    });
  },

  async show(vmContext) {
    try {
      // #ifdef H5
      if (!this.instance) {
        await this.initH5Popup(vmContext);
      }
      return new Promise((resolve) => {
        this.instance.$once("agreed", (agreed) => {
          resolve(agreed);
        });
        this.instance.show();
      });
      // #endif

      // #ifdef APP-PLUS
      // return this.showNativePopup();
      // #endif
    } catch (e) {
      console.error("弹窗失败:", e);
      return false;
    }
  },

  // H5环境初始化
  initH5Popup(vmContext) {
    return new Promise((resolve) => {
      const el = document.createElement("div");
      document.body.appendChild(el);
      const PrivacyComponent = Vue.extend(PrivacyPopup);

      this.instance = new PrivacyComponent({
        parent: vmContext,
      });

      this.instance.$mount(el);
      resolve();
    });
  },

  // App环境使用原生弹窗
  showNativePopup() {
    return new Promise((resolve) => {
      // 先显示协议内容
     
      uni.showModal({
        title: "隐私协议",
        content:
          "请您务必审慎阅读、充分理解《用户协议》和《隐私协议》各条款。我们非常重视您的个人信息和隐私保护，在您使用服务前，请仔细阅读相关协议。",
        confirmText: "查看协议",
        cancelText: "暂不同意",
        success: (res) => {
          if (res.confirm) {
            // 用户点击"查看协议"，跳转到协议页面
            uni.navigateTo({
              url: "/pages/public/richtext?id=2",
              success: () => {
                // 协议页面查看后，再次弹出确认框
                // setTimeout(() => {
                // 	this.showAgreementConfirm(resolve)
                // }, 1000)
                resolve(true);
              },
            });
          } else {
            // 用户点击"暂不同意"
            resolve(false);
          }
        },
        fail: () => {
          resolve(false);
        },
      });
    });
  },

  // 显示协议确认框
  showAgreementConfirm(resolve) {
    uni.showModal({
      title: "确认协议",
      content: "我已阅读并同意《用户协议》和《隐私协议》",
      confirmText: "同意",
      cancelText: "不同意",
      success: (res) => {
        if (res.confirm) {
          resolve(true);
        } else {
          resolve(false);
        }
      },
      fail: () => {
        resolve(false);
      },
    });
  },

  hide() {
    this.instance?.$refs.popup.close();
  },

  destroy() {
    if (this.instance?.$el.parentNode) {
      document.body.removeChild(this.instance.$el);
    }
    this.instance = null;
  },
};

export default PrivacyService;
